clear
set more off
timer on 1
set seed 123
#delim ;
local programs "balance_sheet size_restrictions transactions events 
merging other main" ;
#delim cr
foreach p of local programs {
capture program drop `p'
}

**************** 
***  PATHS   ***  
****************
*BCCR: 1 if at Central Bank
global BCCR=1
if $BCCR == 1 {
	global path "Y:/Projects/MNC_Suppliers/Suppliers_Alfaro-Urena_Manelici_Vasquez"
}

if $BCCR == 0 {
	global path "~/Documents/GitHub/Suppliers_Alfaro-Urena_Manelici_Vasquez"
}
cd $path 
capture mkdir temp
capture mkdir processed_data

*log file
if "${restrictions}"=="" & "${mnc_filename}"=="" & "${size_restriction}"=="" & "${sector_restriction}"=="" {
local logfile "${path0}/log_files/1-event_data_creation"
set linesize 255
log using `logfile', replace
}

set linesize 255

global mnc_size=100
if "${mnc_rtr}"=="mncsize_" {
global mnc_size=$mnc_size_
}

// CONSTRUCTING DATA FOR EVENT STUDY ANALYSIS

***
*** ALFARO-URENA, MANELICI & VASQUEZ
***

********************** 
***  OUTPUT FILES   **  
**********************
global events_data ""processed_data/events_data${restrictions}${mnc_filename}${size_restriction}${sector_restriction}.dta""
global MNCs ""processed_data/MNC_sample${restrictions}${mnc_filename}${size_restriction}${sector_restriction}.dta""
global MNCs2 ""processed_data/MNC_groups${restrictions}${mnc_filename}${size_restriction}${sector_restriction}.dta""

********************** 
***  INPUT FILES   ***  
**********************
global revec_group ""raw_data/revec_group.dta""
global transactions ""raw_data/trans_clean_corresp.dta""
global revec_corresp ""raw_data/revec_corresp.dta""
global fsh_source ""raw_data/all_foreign.dta""
global compliance ""raw_data/d151_compliance.dta""

********************************************************************************
* main program: outline of the full code
********************************************************************************
prog main

*balance sheet data
display "balance sheet data"
	quiet balance_sheet

*size and sector restrictions
display "size and sector restrictions"
	quiet size_restrictions

*transactions dataset
display "transactions dataset"
	quiet transactions
	
*information about events
display "information about events"
	quiet events
	
*merging data	
display "merging data"
	quiet merging 
	
*extra variables
display "creating extra variables"
	quiet other
	
end

********************************************************************************
*balance sheet data
********************************************************************************
prog balance_sheet
display "balance_sheet"

use $revec_group, clear
compress
keep ID sophistication corp empresarial estado_* sector_institucional ///
 ipubgrupo inolucrogrupo nombre_r provincia firm_AE firm_ciiu4 ingresosir_* ///
 trabaj_* salarios_* va_* exports_* imports_* entry exit sector_g ZF* ///
 foreign_l* total_activo_neto_* activos_fijos_* costo_de_ventas_* 

**  CONVERTING TO REAL VALUES 
* money in millions
local money_col "ingresosir va costo_de_ventas total_activo_neto activos_fijos "
forvalue year =2005/ $last_year_revec {
foreach vari of local money_col{
replace `vari'_`year'= (100*(`vari'_`year')/${ipc`year'})/1000000 
format `vari'_`year' %16.0g
}
}
* money in Th
local money_col "salarios"
forvalue year =2005/ $last_year_revec {
foreach vari of local money_col{
replace `vari'_`year'= (100*abs(`vari'_`year')/${ipc`year'})/1000
format `vari'_`year' %16.0g
}
}

** IMPORTS AND EXPORTS ARE IN DOLLARS (we convert them to colones)
local money_dol "exports imports"
forvalue year =2005/ $last_year_revec {
foreach vari of local money_dol{
replace `vari'_`year'= ${tc_`year'}*(100*abs(`vari'_`year')/${ipc`year'})/1000000
format `vari'_`year' %16.0g
}
}

** RESHAPING
local resh_var "ingresosir_ costo_de_ventas_ trabaj_ estado_ salarios_ va_ exports_ imports_ ZF_broad_ total_activo_neto_ activos_fijos_"
reshape long `resh_var', i(ID) j(year)
compress

* we keep data for the same period as in the transactions dataset for consistency
drop if year<2008
local yearplus= $last_year_revec + 1
drop if year==`yearplus'
destring firm_ciiu4, gen(sector4)
gen sector3=floor(sector4/10)
gen sector2=floor(sector3/10)

label variable salarios_ "Wage bill" 
label variable exports_ "Exports" 
label variable imports_ "Imports" 
label variable ingresosir_ "Total Sales" 
label variable trabaj_ "Employment" 
label variable va_ "Value Added" 
label variable costo_de_ventas_ "Input Costs" 
label variable total_activo_neto_ "Total Net Assets" 

save temp/revec_all.dta, replace
end

********************************************************************************
*size and sector restrictions
********************************************************************************
prog size_restrictions
display "size and sector restrictions"
*using previous data
use temp/revec_all.dta, clear

*** only keep firm-year pairs with both workers and sales 
drop if ingre==. | trabaj==.
replace total_activo_neto=. if total_activo_neto==0
replace costo_de_ventas=. if costo_de_ventas==0

* ZONAS FRANCAS
gen ZF_tot=(ZF+ZF_b>0)
bys ID: egen Zona_F= max(ZF_t)
drop ZF ZF*
* GEOGRAPHIC INFORMATION
drop if provincia==""
* NO HOUSEHOLDS
replace sector_institucional=substr(sector_institucional, 1, 3)

* NO GOVERNMENT, NO NGO
drop if inolucrogrupo==1 | ipubgrupo==1

* NO ELECTRICITY AND GAS or WATER (Public also) 
drop if sector_g==3 & foreign_list!=1
drop if sector_g==4 & foreign_list!=1
* WITHOUT SECTOR
drop if sector_g==.

* active firms: they have both workers and sales
gen estado=(ingresosir>1 & trabaj>1)
bys ID: egen max_estado=max(estado)
drop max_estado
keep if estado==1

** NO HOLES IN DATA
bys ID: gen numb_obs=_N
bys ID: egen min_y=min(year)
bys ID: egen max_y=max(year)
gen numb_years=max_y-min_y+1
gen gap=numb_years-numb_obs
*no gap years in data for domestic firms
keep if gap==0 | forei==1 
drop gap
*firms should appear more than one year
drop if numb_o==1 & forei==0 & entry!=$last_year_revec
drop min max numb*
* MEDIAN WORKERS & SALES
bys ID: egen med_w_=median(trabaj_)
bys ID: egen med_ing=median(ingresosir)

*activating sector restrictions for robustness checks
if "$sector_restriction"!="sect_" {
*only non-financial private sector (excluding households)
keep if sector_ins=="S11"
drop sector_ins

*no CONSTRUCTION/Real estate or EDUCATION or FINANCIAL
drop if sector_g==5 & foreign_list!=1
drop if sector_g==10 & foreign_list!=1
drop if sector_g==13 & foreign_list!=1
drop if sector_g==17 & foreign_list!=1
}

*activating size restrictions for robustness checks
if "$size_restriction"!="domsize_" {
* Drop if median of workers for suppliers is smaller than:
drop if med_w<=3 | med_w==.
* drop if the median of the sales is smaller than 50k
drop if med_ing<=50 | med_ing==.
}

*** DEFINITION OF MNC
preserve
use $fsh_source, clear
keep ID fuente1
tempfile fuente
save `fuente', replace
restore
merge m:1 ID using `fuente'
drop if _m==2
drop _m
gen MNC=((med_w>= $mnc_size & med_w!=. & foreign_list==1 & fuente1!="PART OF GROUP")==1 | (Zona_F==1 & foreign_list==1)==1)
drop med* fuente

sort ID, stable
by ID: gen dup=cond(_N==1,0,_n)
preserve
keep if MNC==1
* UNIQUE IDS
drop if dup>1
keep ID corp empresarial foreign entry nombre_rev firm_AE firm_ciiu4 provincia 
save $MNCs, replace
rename ID ID_group
merge 1:m ID_group using $revec_corresp
keep if _m==3
keep ID ID_g corp empresarial nombre_rev
order ID ID_g nombre_rev corp empresarial, first   
save $MNCs2, replace
restore
drop dup

*saving 
save temp/dom.dta, replace
end

********************************************************************************
*transactions
********************************************************************************
prog transactions
display "including transactions data"
*using previous data
use temp/dom.dta, clear

***PREPARING FOR TRANSACTIONS	   

* SELLERS
preserve
keep if foreign==0
rename * s_*
rename s_ID seller
rename s_year year
rename s_nombre s_name
compress
save temp/sellers.dta, replace
keep seller year s_entry s_exit s_ingre
sort seller year, stable
by seller year: gen dup=cond(_N==1,0,_n)
drop if dup>1
drop dup
save temp/sellers_id.dta , replace
restore

* BUYERS  
preserve
rename * b_*
rename b_ID buyer
rename b_year year
rename b_nombre b_name
replace b_name=substr(b_name, 1, 60)
keep buyer b_MNC b_sophistication b_entry b_firm_AE b_firm_ciiu4 b_sector_g b_provincia b_Zona_F  b_name 
sort buyer, stable
by buyer: gen dup=cond(_N==1,0,_n)
drop if dup>1
drop dup
save temp/buy_.dta, replace
restore

* ONLY MNC
preserve
keep if MNC==1
keep ID
bys ID: gen dup=cond(_N==1,0,_n)
drop if dup>1
drop dup
rename ID buyer
save temp/f_buyer.dta, replace
rename buyer seller
save temp/f_seller.dta, replace 
restore

*** SELLERS AND TRANSACTIONS: TOTAL SALES 
use $transactions, clear
*some transactions appear to be larger than the reported revenues of
*the seller. Those are labelled as "potentially wrong." We exclude them
drop if pot==1
drop pot

* TRANSACTIONS TO REAL VALUE
local trans_vari "trans"
foreach v of local trans_vari{
forvalue i=2008/ $last_year_revec {
replace `v'=(100*(`v')/${ipc`i'})/1000000 if year==`i'
}
}
save temp/trans_real.dta, replace 

merge m:1 buyer using temp/f_buyer.dta
gen fore_buyer=(_m==3)
drop if _m==2
drop _m
merge m:1 seller using temp/f_seller.dta
gen fore_seller=(_m==3)
drop if _m==2
drop _m

* TOTAL PURCHASES PER FIRM
preserve
collapse (sum) trans, by(buyer year)
rename buyer ID
rename trans purchases
save temp/purch.dta, replace
restore

* NUMBER OF SUPPLIERS
preserve
bys buyer year: gen n_suppliers=_N
bys buyer year: egen n_fore_suppliers=total(fore_seller)
collapse n_suppliers n_fore_suppliers, by(buyer year)
rename buyer ID
save temp/n_sup.dta, replace
restore

* NUMBER OF CLIENTS
preserve
sort seller year, stable
by seller year: gen n_clients=_N
by seller year: egen n_fore_clients=total(fore_buyer)
collapse n_clients n_fore_clients, by(seller year)
rename seller ID
save temp/n_clients.dta, replace
restore

* MERGING #CLIENTS AND #SUPPLIERS
preserve
use temp/n_clients.dta, clear
merge 1:1 ID year using temp/n_sup.dta
drop _m
save temp/n_clients.dta, replace
capture capture erase temp/n_sup.dta
restore

* sellers transactions
merge m:1 seller year using temp/sellers_id.dta
drop if _m==1
gen tot_trans_mnc=fore_buyer*trans
collapse (sum) trans tot_trans_mnc (mean) s_ingre , by(seller year)
rename trans all_trans
replace all_trans=s_ingre if all_trans>s_ingre & all_trans!=.
replace tot_trans_mnc=s_ingre if tot_trans_mnc>s_ingre & tot_trans_mnc!=.
drop s_ingre
save temp/all_trans.dta, replace

*** MERGING FOREIGN BUYERS AND TRANSACTIONS DATA  
use temp/sellers_id.dta, clear
merge 1:m seller year using $transactions
keep if _m==3
drop if pot==1
bys seller year: egen tot_trans=total(trans_)
keep seller buyer trans year s_ing  tot_trans
save temp/temp_trans.dta, replace

use temp/buy_.dta, clear
keep if b_MNC==1
merge 1:m buyer using temp/temp_trans.dta
drop if year<2008 
keep if _m==3
drop _m 
* TRANSACTIONS TO REAL VALUE
local trans_vari "trans tot_trans"
foreach v of local trans_vari{
forvalue i=2008/ $last_year_revec {
replace `v'=(100*(`v')/${ipc`i'})/1000000 if year==`i'
}
}

*saving 
save temp/trans_all.dta, replace

capture erase temp/sellers_id.dta
capture erase temp/buy_.dta
capture erase temp/f_buyer.dta
capture erase temp/f_seller.dta
capture erase temp/n_sup.dta

end

********************************************************************************
*information about events
********************************************************************************
prog events
display "information about events"
*using previous data
use temp/trans_all.dta, clear 

*** no events because firms already sold to MNCs
preserve
* EVENTS
bys seller: egen event=min(year)
*we want to make as probable as possible that we observe the first interaction
gen past_treated=1 if event==2008 | event==2009
replace event=. if past==1
collapse event past_t , by(seller)
tempfile past_tr
save `past_tr'
restore
merge m:1 seller using `past_tr'
drop _m 

*** INFO OF THE MNC THAT TRIGGERED THE EVENT  
preserve
drop if past_treated==1 | buyer==""
* NUMBER OF MNC CLIENT THAT TRIGGERED THE EVENT, BY YEAR
gen temp_trig_MNC=(year==event)
bys buyer seller: egen n_trig_MNC=max(temp_tr)
collapse (sum) n_trig_MNC, by(seller year)
rename seller ID
save temp/n_triggers.dta, replace
restore 

preserve
drop if past_treated==1 | buyer==""
* firms receiving one event
sort seller year, stable
by seller year: gen num_mnc=_N if year==event
by seller: egen mean_num=mean(num_mnc)
gen one_event=(mean_num==1)

* KEEPING INFO (TRANSACTIONS, ETC) FOR THE SELLER WITH THE FOREIGN FIRM 
*THAT TRIGGERING THE EFFECT

sort seller buyer, stable
by seller buyer: egen min_y=min(year)
replace min_y=. if tran==.
keep if min_y==event
gen temp_s=-b_sop
gen temp_m=(b_sector_g==2)
sort seller year b_Zona_F temp_s temp_m trans , stable
drop temp*
by seller year: egen trans2=max(trans)
by seller year: gen event_b=_n
by seller year: gen temp2_event_b=_N
replace event_b=(event_b==temp2_event_b & year==event)
*SOME TIMES THERE IS MORE THAN ONE BUYER. We keep the info of the MNC
*with the highest trans that year
gen event_multiple=(year==event)
sort seller buyer, stable
by seller buyer: egen temp_event_b=max(event_b)
by seller buyer: egen temp_event_m=max(event_multiple)
replace event_b=(temp_event_b==1)
replace event_m=(temp_event_m==1)
drop temp*
sort seller year event_m event_b , stable
by seller year: gen temp1=_n
by seller year: gen temp2=_N
by seller year event_m: egen trans_mncs_event=total(trans_)
gen sh_trans_mnc=trans_mncs_event/tot_trans
replace trans_mncs_event=sh_trans_mnc*s_ingre if tot_trans>s_ingre & tot_trans!=.
drop sh_trans*
keep if temp1==temp2
drop temp*
drop if  event_b==0
rename trans2 trans_first_mnc
replace trans_first_mnc=s_ingr if trans_first_mnc>s_ingr & trans_first_mnc!=.
replace trans_mncs_event=s_ingr if trans_mncs_event>s_ingr & trans_mncs_event!=.
keep seller buyer year trans_first_mnc trans_mncs_event  b_* one_event
bys seller year: gen dup=cond(_N==1,0,_n)
drop if dup>1
drop dup
compress
save temp/seller_mnc.dta, replace

*** LIST OF SELLERS TO BE USED
sort seller, stable
by seller: gen dup=cond(_N==1,0,_n)
drop if dup>1
drop dup trans* year
save temp/seller_list.dta, replace
restore
collapse  event past_treated , by(seller year)

*saving file
save temp/premerging.dta, replace
end

********************************************************************************
*merging data
********************************************************************************
prog merging
display "merging data"
*using previous dataset
use temp/premerging.dta, clear

*  	MERGING THE SELLERS WITH THEIR RESPECTIVE BALANCE SHEETS
merge 1:1 seller year using temp/sellers.dta
drop if _m==1
sort seller, stable
by seller: egen merge_yes=max(_m)
gen treated=(merge_yes==3)
drop _m merge_yes

compress
merge m:1 seller using temp/seller_list.dta
drop _m
merge m:1 seller year using temp/seller_mnc.dta
drop _m

local vari1 "event past_treated"
foreach v of local vari1 {
sort seller, stable
by seller: egen temp_`v'=mean(`v')
drop `v' 
rename temp_`v' `v'
}
replace past=0 if past==.
rename s_* *
replace name=substr(name, 1, 60)
compress
merge 1:1 seller year using temp/all_trans.dta
drop if _m==2
* we consider events no later than 2015
local last_event= $last_year_revec - 2
drop if event>`last_event' & event!=.
drop _m

*MERGING REMAINING DATASETS
gen treated2=(treated==1 & past_treated==0)
sort sector4, stable
by sector4: egen tre=max(treated2)
replace tre=1 if past==1
*drop firms in sectors that are not treated
drop if tre==0 
drop tre treated2
rename seller ID

* keep only firms for which we observe balance sheet data in the year of the event
gen temp_event_yes=(year==event)
bys ID: egen event_yes=max(temp_event_yes)
replace event_yes=. if event==.
drop if event_y==0
drop event_y temp*

* MERGE D151 COMPLIANCE
merge 1:1 ID year using $compliance
drop if _m==2
drop _m

* MERGE # CLIENTS AND # SUPPLIERS
merge 1:1 ID year using temp/n_clients.dta
drop if _m==2
drop _m
replace n_cl=1 if n_cl==. & year>=2008
merge 1:1 ID year using temp/n_triggers.dta
drop if _m==2
drop _m
replace n_trig=0 if n_trig==.

* MERGE PURCHASES FROM D151
merge 1:1 ID year using temp/purch.dta
drop if _m==2
drop _m
replace purchas=0 if purchas==. & year>=2008
replace trans_first_mnc=0 if trans_first_mnc==. & event!=. & year>event
replace tot_trans_mnc=0 if tot_trans_mnc==. & year>=2008
replace trans_mncs_event=0 if trans_mncs_event==. & year>=2008

*saving final output data
save $events_data, replace
end 

********************************************************************************
*other variables
********************************************************************************
prog other
display "other variables"
*use previous data
use $events_data, clear

* PRODUCTIVITY INDEX
gen ok= (ingresos!=. & trabaj!=. & total_activo!=. & costo_de_ven!=. & costo_de_ven!=0)
bys sector2 : egen sum_y=total(ingresos) if ok==1
gen sala2=salarios/1000
bys sector2 : egen sum_sal=total(sala2) if ok==1
bys sector2 : egen sum_mat=total(costo_de_ven) if ok==1

gen sh_salarios=sum_sal/sum_y
gen sh_mat=sum_mat/sum_y

drop sum* sala2 ok
** Assuming CRS (not to estimate cost of capital)
gen prod= log(ingresos)-sh_sala*log(trabaj_)-sh_mat*log(costo_de_ve)-(1-sh_sala-sh_mat)*log(total_activo)
save temp/final_pre.dta, replace

* NEW/OLD SUPPLIERS, SECTORS, ETC
* FIRMS THAT EXPERIENCED AN EVENT
keep event past ID year
tempfile events
save `events', replace

use temp/revec_all.dta, clear
* NO GOVERNMENT, NO NGO
drop if inolucrogrupo==1 | ipubgrupo==1

keep ID year ingresos costo_de_ imports sophistication exports_  trabaj_  sector*
merge 1:1 ID year using `events'
drop _m
preserve
rename * s_*
rename s_ID seller
rename s_year year
tempfile as_seller
save `as_seller', replace
restore 

rename * b_*
rename b_ID buyer
rename b_year year
tempfile as_buyer
save `as_buyer', replace

* MNCS LIST
use $MNCs, clear
keep ID
rename ID buyer
tempfile MNC_buyer
save `MNC_buyer', replace
rename buyer seller
tempfile MNC_seller
save `MNC_seller', replace
* TRANSACTIONS
use temp/trans_real.dta, clear
* MERGING FIRMS
merge m:1 buyer year using `as_buyer'
gen buyer_data=(_m==3)
drop if _m==2
drop _m
merge m:1 seller year using `as_seller'
gen seller_data=(_m==3)
drop if _m==2
drop _m
keep if buyer_data==1 | seller_data==1
* WHICH ARE MNCS
merge m:1 buyer using `MNC_buyer'
gen buyer_mnc=(_m==3)
drop if _m==2
drop _m
merge m:1 seller using `MNC_seller'
gen seller_mnc=(_m==3)
drop if _m==2
drop _m
* MNC TRIGGERING EVENT
gen mnc_event=(year==s_event & buyer_mnc==1)
bys buyer seller: egen mnc_trig=max(mnc_event)
*** CHARACTERISTICS OF BUYERS (EXCLUDING MNC TRIGGERING)
* weights: transactions
gen tr_not_triggering=trans
replace tr_not_triggering = . if mnc_trig==1
bys seller year: egen weight=total(tr_not_triggering)
replace weight=tr_not_triggering/weight

gen sophis1=(b_sophistication==1)
gen sophis2=(b_sophistication==1 | b_sophistication==2)
replace  b_exports_=0 if  b_exports_==. 
replace  b_imports_=0 if  b_imports_==.
gen firms=1
bys buyer year: egen b_purch=total(trans_)
bys buyer year: egen b_nsuppliers=total(firms)
gen b_trans_per_seller=b_purch/b_nsuppliers
 *length:
bys seller buyer: gen b_length_suppliers=_N
preserve 
collapse (sum) firm , by(seller year)
rename firm b_nclients
rename seller buyer
tempfile clients
save `clients', replace
restore
merge m:1 buyer year using `clients'
replace b_nclients=1 if _m==1
drop if _m==2
drop _m 
gen b_sh_exp=b_exports_/b_ingresosir_
gen b_sh_imp=b_imports_/(b_purch+b_imports)
 local ave "b_trabaj_ b_ingresosir_ b_exports_ b_imports_ sophis1 sophis2 b_sh_exp b_sh_imp b_nsuppliers b_nclients b_length_suppliers b_trans_per_seller"
* AVERAGES
foreach v of local ave{
replace `v'=. if b_ingresosir_==. | b_trabaj_==.
gen ave_`v'=`v'*weight
replace ave_`v'=. if mnc_trig==1
}
*** NUMBER OF SECTORS SELLING TO
 preserve
 keep buyer seller year b_sector* mnc_trig
 drop if mnc_trig==1
 forvalue i=2/4{
 replace b_sector`i'=99999 if b_sector`i'==.
 egen num_sector`i'_sell=tag(seller year b_sector`i')
 }
 collapse (sum) num_sector* , by(seller year)
 tempfile sectors_sell
 save `sectors_sell', replace
 restore
 merge m:1 seller year using `sectors_sell'
 ds num_s*
 foreach v in `r(varlist)'{
 replace `v'=1 if `v'==. & _m==1
 }
 drop _m
 *** NUMBER OF SECTORS SELLING TO
forvalue i=2/4{
replace s_sector`i'=99999 if s_sector`i'==.
egen num_sector`i'_buy=tag(buyer year s_sector`i')
replace s_sector`i'=. if s_sector`i'==99999
}

*** Sales to firms the did not experience the event themselves
* sales to buyers that experienced the demand shock (to rule out pure input-output effects)
gen double trans_evented= trans*(year>=b_event & b_event!=.)
bys seller year: egen tot_trans=total(trans_)
bys buyer year: egen tot_purch=total(trans_)
*sales to firms that are not suppliers to MNCs 
gen double trans_to_suppliers= trans_*((year>=b_event & b_event!=.) | b_past_treated==1)


* VARIABLES FOR SELLERS
preserve 
collapse (mean) s_ingresosir_ num_sector4_sell num_sector3_sell num_sector2_sell (sum) trans_  trans_evented trans_to_suppliers ave_*, by(seller year)
gen sh_trans_evented=trans_evented/trans_
replace trans_evented=s_ingresos*sh_trans_evented if trans_>s_ingresosir_ & trans_!=. & s_ingresosir_!=.
gen sh_2=trans_to_suppliers/trans_
replace trans_to_suppliers=s_ingresos*sh_2 if trans_>s_ingresosir_ & trans_!=. & s_ingresosir_!=.

drop sh* trans_ s_ingresosir_

rename seller ID
tempfile seller_trans
save `seller_trans', replace 
restore
* VARIABLES FOR BUYERS
preserve 
collapse (sum) num_sector4_b num_sector3_b num_sector2_b , by(buyer year)
rename buyer ID
tempfile buyer_trans
save `buyer_trans', replace 
restore

* MERGING WITH FINAL DATA
use temp/final_pre.dta, clear
merge 1:1 ID year using `seller_trans'
drop if _m==2
drop _m
merge 1:1 ID year using `buyer_trans'
drop if _m==2
ds num_*buy
foreach v in `r(varlist)'{
replace `v'=1 if `v'==.
}
drop _m
local tr "trans_evented trans_to_suppliers"
foreach v of local tr{
replace `v'=0 if `v'==.
}
********************** 
***  OUTPUT FILES   **  
**********************
save $events_data, replace

end

********************************************************************************
* EXCHANGE RATE AND PRICES 
********************************************************************************
quiet{
************************************************************ 
***  PRODUCER PRICE INDEX  (yearly average) 2013 ==100    **  
************************************************************  	
global ipc2005 = 50.99*100/92.88
global ipc2006 = 57.96*100/92.88
global ipc2007 = 63.38*100/92.88
global ipc2008 = 75.43*100/92.88
global ipc2009 = 77.53*100/92.88
global ipc2010 = 81.15*100/92.88
global ipc2011 = 85.57*100/92.88
global ipc2012 = 89.78*100/92.88
global ipc2013 = 92.88*100/92.88
global ipc2014 = 98.99*100/92.88
global ipc2015 = 98.93*100/92.88
global ipc2016 = 100.08*100/92.88
global ipc2017 = 100.77*100/92.88
global ipc2018 = 103.27*100/92.88
global ipc2019 = 106.25*100/92.88
global ipc2020 = 106.08*100/92.88
global ipc2021 = 107.61*100/92.88

********************************* 
***  AVERAGE EXCHANGE RATE    ***  
*********************************
* 1 March of each year: average compra-venta
global tc_2005=477.76578
global tc_2006=511.29055
global tc_2007=516.59063
global tc_2008=526.35683
global tc_2009=573.35611
global tc_2010=525.68364
global tc_2011=505.69
global tc_2012=502.8868
global tc_2013=499.75405
global tc_2014=538.36123
global tc_2015=534.55408
global tc_2016=544.76658
global tc_2017=567.55509
global tc_2018=573.80312
global tc_2019=583.82885
global tc_2020=581.54811
global tc_2021=611.75618
}

******************************************************************************** 
***  EXECUTE THE PROGRAM main   
********************************************************************************
main

******************************************************************************** 
*** ERASING TEMP DATA
********************************************************************************
capture erase temp/revec_all.dta
capture erase temp/dom.dta
capture erase temp/trans_all.dta
capture erase temp/all_trans.dta
capture erase temp/trans_real.dta
capture erase temp/sellers.dta
capture erase temp/seller_list.dta
capture erase temp/seller_mnc.dta
capture erase temp/final_pre.dta

******************************************************************************** 
***  TIMER
********************************************************************************
if "${restrictions}"=="" & "${mnc_filename}"=="" & "${size_restriction}"=="" & "${sector_restriction}"=="" {
timer off 1
*time in seconds
timer list 1
*time in minutes
local time_ =round(`r(t1)'/60)
display "the code takes `time_' minutes in total"

log close
translate `logfile'.smcl `logfile'.txt , replace linesize(255)
capture erase `logfile'.smcl
}
